﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using PSE.Framework.Threading;
using System.Configuration;
using PSE.AuditLogging.StorageService.Configuration;
using PSE.AuditLogging.Common.Configuration;
using PSE.Framework.ErrorLogging;
using PSE.Framework.Process;
using PSE.Framework.Configuration;

namespace PSE.AuditLogging.StorageService.Instance
{
    class Program : BaseProgram
    {
        static Program()
        {
            Initialize(PSE.Framework.Configuration.Components.SystemComponents.System, PSE.Framework.Configuration.Components.SystemComponents.AuditLoggingStorageService);
        }

        static CrossProcessManualResetEvent _mreNotifyParent;//notificar o parent que o processo filho foi criado com sucesso
        static CrossProcessManualResetEvent _mreExecutionControl;//controlar a execucao do processo filho (o processo pai pode parar o processo filho sem kill)

        static Thread _thrCheckParentAlive;

        static int _parenteProcessPID;

        static void Main(string[] args)
        {
            try
            {
                if (args.Length != 3)
                    throw new ArgumentException("Parameters 'productId', 'instanceId' and 'parentProcessPID' missing");

                string productId = args[0];
                string instanceId = args[1];
                _parenteProcessPID = Convert.ToInt32(args[2]);

                //Notificar ao parent que o processo foi iniciado com sucesso
                _mreNotifyParent = new CrossProcessManualResetEvent(false, "PSE.AuditLogging.StorageService.MRENotifyParent_" + productId + "_" + instanceId);
                _mreNotifyParent.Set();

                _mreExecutionControl = new CrossProcessManualResetEvent(false, "PSE.AuditLogging.StorageService.MREExecutionControl_" + productId + "_" + instanceId);

                //validar as configuracoes, c aso nao estejam ok, sera disparada uma exception e o processo será finalizado
                ValidateConfigurations(productId, instanceId);

                _thrCheckParentAlive = new Thread(CheckParentAlive);
                _thrCheckParentAlive.Start();

                using (LogStorer storer = new LogStorer(productId, instanceId, _mreExecutionControl))
                {
                    storer.Execute();
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.WriteLog(LogType.Error, "Unable to start Audit Logging Instance." + Environment.NewLine + ex.ToString());
            }
            finally
            {
                if (_mreNotifyParent != null)
                    _mreNotifyParent.Set();

                if (_mreExecutionControl != null)
                    _mreExecutionControl.Set();
            }
        }

        private static void ValidateConfigurations(string productId, string instanceId)
        {
            //verificar se o produto informado consta nas configuracoes
            if (ConfigurationReader.LogServiceConfiguration.Products[productId] == null)
                throw new ConfigurationErrorsException("The informed product its not configured.");

            //verificar se a instancia informada consta nas configuracoes
            if (ConfigurationReader.LogServiceConfiguration.Products[productId].Instances[instanceId] == null)
                throw new ConfigurationErrorsException("The informed instance its not configured.");

            List<string> logTypes = new List<string>();

            foreach (StorageConfigurationElement storage in ConfigurationReader.LogServiceConfiguration.Products[productId].Instances[instanceId].Storages)
            {
                foreach (LogTypeConfigurationElement logTypeConfig in storage.LogTypes)
                {
                    if (logTypes.Contains(logTypeConfig.Id))
                    {
                        //duplicado
                        throw new ConfigurationErrorsException(string.Format("The instance '{0}' has a log type set to more than one storage.", instanceId));
                    }
                    else
                        logTypes.Add(logTypeConfig.Id);
                }
            }
        }

        private static void CheckParentAlive()
        {
            while (!_mreExecutionControl.WaitOne(300))//enqnto o processo n for finalizado
            {
                Process parentProcess = Process.GetProcesses().FirstOrDefault(p => p.Id == _parenteProcessPID);

                if (parentProcess != null)
                {
                    parentProcess.Refresh();
                    if (parentProcess.HasExited)
                        _mreExecutionControl.Set();//finalizar a execucao do processo atual pois o pai nao esta mais executando
                }
                else
                    _mreExecutionControl.Set();//finalizar a execucao do processo atual pois o pai nao esta mais executando
            }
        }
    }
}
